// 自动化操作的代码
const addConfig = require('./addConfig')
const fs = require('fs')
const path = require('path')
const shell = require('shelljs')
shell.echo('>>>>>>')
shell.echo('开始新建页面')
addConfig.forEach((ele) => {
  if (ele.open) {
    buildPage(ele)
  }
})

function buildPage(config) {
  const paths = path.resolve(`./src/views/${config.name}`)
  shell.echo('页面地址:' + paths)
  fs.mkdir(paths, function() {
    let str = ''
    if (config.helloworld) {
      // 新建空白页，读取空白页模版
      str = handleStr(
        fs.readFileSync(path.resolve('./auto-build-page/template-helloworld.vue')),
        config
      )
    } else {
      str = handleStr(
        fs.readFileSync(path.resolve('./auto-build-page/template-table.vue')),
        config
      )
    }
    // 写入文件
    writeFileSync(paths + '/index.vue', str)
    shell.echo('开始新增路由……')
    addRou(`../../src/views/${config.name}/index.vue`, config)
  })
}

// 同步写入
function writeFileSync (filePath, str) {
  fs.writeFileSync(filePath,str,(err)=>{
    if(err){
      shell.echo('writeFileSync err:' + err)
      return
    }
    // shell.echo('writeFileSync:写入成功！')
  })
}

function handleStr(str, config) {
  if (config.helloworld) {
    return str
  }
  str = str.toString().replace('%title%', config.desc)
  return str
}

// 添加路由
function addRou(paths, config) {
  shell.echo('paths……', paths)
  shell.echo('config……', config)
  const templateStr = handleRouStr(
    fs.readFileSync(path.resolve('./auto-build-page/template-route.txt')),
    config,
    paths
  )
  // 添加到路由文件
  addToConf(templateStr)
}
function handleRouStr(str, config, paths) {
  str = str.toString().replace(/%path%/g, `/${config.name}`)
  str = str.toString().replace(/%name%/g, config.desc)
  str = str.toString().replace(/%name2%/g, `${config.desc}首页`)
  str = str.toString().replace(/%repath%/g, `/${config.name}/index`)
  str = str.toString().replace(/%requirepath%/g, paths)
  str = str.toString().replace(/%requireAuth%/g, Boolean(`${config.meta.requireAuth}`))
  return str
}

// 将路由添加到vue项目src下的routes.js文件
function addToConf(str) {
  str += '// add-flag' // 添加的位置标记
  const confStr = handleConfRouStr(fs.readFileSync(path.resolve('./src/router/addRoute.js')), str)
  writeFileSync(path.resolve('./src/router/addRoute.js'), confStr)
  shell.echo('str:'+ str.name)
  shell.echo('confStr:'+ confStr.addRoute)
  shell.echo('路由添加成功!')
  shell.echo('结束生成页面')
  shell.echo('>>>>>>')
}
function handleConfRouStr(ori, str) {
  ori = ori.toString().replace('// add-flag', str)
  return ori
}





